package com.leadingsoft.web.service;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.leadingsoft.core.mapper.KJobDao;
import com.leadingsoft.core.model.KJob;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.leadingsoft.common.toolkit.Constant;
import com.leadingsoft.core.dto.BootTablePage;
import com.leadingsoft.core.mapper.KJobRecordDao;
import com.leadingsoft.core.model.KJobRecord;

@Service
public class JobRecordService {

	@Autowired
	private KJobRecordDao kJobRecordDao;
	@Autowired
	private KJobDao kJobDao;
	
	/**
	 * @Title getList
	 * @Description 获取带分页的列表
	 * @param start 起始行数
	 * @param size 每页行数
	 * @param uId 用户ID
	 * @param jobId 作业ID
	 * @return
	 * @return BootTablePage
	 */
	public BootTablePage getList(Integer start, Integer size, Integer uId, Integer jobId){
		KJobRecord template = new KJobRecord();
		template.setAddUser(uId);
		if (jobId != null){
			template.setRecordJob(jobId);
		}
		List<KJobRecord> kJobRecordList = kJobRecordDao.template(template, start, size);
		if(CollectionUtils.isNotEmpty(kJobRecordList)) {
			// 根据JOBID查询JOB
			Set<Integer> jobIds = kJobRecordList.stream().map(KJobRecord::getRecordJob).collect(Collectors.toSet());
			StringBuilder sb = new StringBuilder();
			sb.append("select job_id, job_name from k_job where job_id in (");
			int i = 0;
			for (Integer id : jobIds) {
				if(i == 0) {
					sb.append(id);
				} else {
					sb.append("," + id);
				}
				i++;
			}
			sb.append(")");
			List<KJob> jobs = kJobDao.execute(sb.toString());
			Map<Integer, String> jobMap = jobs.stream().collect(Collectors.toMap(KJob::getJobId, KJob::getJobName));
			kJobRecordList.forEach(r -> {
				r.setRecordJobName(jobMap.get(r.getRecordJob()));
			});
		}
		long totalCount = kJobRecordDao.templateCount(template);
		BootTablePage bootTablePage = new BootTablePage();
		bootTablePage.setRows(kJobRecordList);
		bootTablePage.setTotal(totalCount);
		return bootTablePage;
	}

	@Value("${kettle.log.file.path}")
	private String kettleLogFilePath;
	
	/**
	 * @Title getLogContent
	 * @Description 转换日志内容
	 * @param jobId 转换记录ID
	 * @return
	 * @throws IOException
	 * @return String
	 */
	public String getLogContent(Integer jobId) throws IOException{
		KJobRecord kJobRecord = kJobRecordDao.unique(jobId);
		String logFilePath = kJobRecord.getLogFilePath();
		return FileUtils.readFileToString(new File(kettleLogFilePath + logFilePath), Constant.DEFAULT_ENCODING);
	}
}